package com.itcm.tcpdemo.components;

import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

public class SseClient {

    private final WebClient webClient;

    public SseClient(String baseUrl, String apiKey) {
        this.webClient = WebClient.builder()
                .baseUrl(baseUrl)
                .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + apiKey)
                .build();
    }

    public Flux<ServerSentEvent> getEvents(String query, String user, String imageUrl) {
        return webClient.post()
                .uri("/v1/chat-messages")
                .bodyValue(createRequestBody(query, user, imageUrl))
                .accept(MediaType.TEXT_EVENT_STREAM)
                .retrieve()
                .bodyToFlux(ServerSentEvent.class);
    }

    private String createRequestBody(String query, String user, String imageUrl) {
        return String.format(
                "{\n" +
                        "    \"inputs\": {},\n" +
                        "    \"query\": \"%s\",\n" +
                        "    \"response_mode\": \"streaming\",\n" +
                        "    \"conversation_id\": \"\",\n" +
                        "    \"user\": \"%s\",\n" +
                        "    \"files\": [\n" +
                        "    ]\n" +
                        "}",
                query, user
        );
    }
}